package com.bis.ymyy.common.utils;

import com.bis.ymyy.common.exception.BusinessException;
import com.bis.ymyy.common.exception.EnumCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BusinessException {

        //添加跨域CORS
/*
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
*/

        String token = request.getHeader("token");
        if (token != null){
            boolean result = TokenUtil.verify(token);
            if (result){
//                log.info("通过验证");
                return true;
            } else {
                log.warn("token验证失败");
                throw new BusinessException(EnumCode.E_100102);
            }
        } else {
            throw new BusinessException(EnumCode.E_100103);
        }
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws BusinessException {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws BusinessException {
    }
}
